﻿using AutoMapper;
using B.S.Filtration.Domain.到货检验;
using B.S.Filtration.ErrorCode;
using B.S.Filtration.Write.Api.Application.Command.到货检验.QualityReportWorkCommand;
using MediatR;
using SqlSugar;

namespace B.S.Filtration.Write.Api.Application.CommandHander.到货检验.QualityReportWorkHandler
{
    /// UpdateQualityReportWorkHandler：这是一个处理 UpdateQualityReportWorkCommand 请求的类，继承自 IRequestHandler 接口。
    public class UpdateQualityReportWorkHandler : IRequestHandler<UpdateQualityReportWorkCommand, APIResult<int>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;
        public UpdateQualityReportWorkHandler(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        public async Task<APIResult<int>> Handle(UpdateQualityReportWorkCommand request, CancellationToken cancellationToken)
        {
            //泛型返回类型：APIResult<int> 表示返回一个封装了整数结果的 API 响应。
            APIResult<int> result = new APIResult<int>();
            //使用 AutoMapper 将 UpdateQualityReportWorkCommand 映射到 QualityReportWork 实体。
            var model = mapper.Map<QualityReportWork>(request);
            //强制将 IsDel 字段设为 false，确保更新后的记录为未删除状态。
            model.IsDel = false;
            //使用 SQLSugar 的 Updateable 方法更新实体，返回受影响的行数。
            result.data = await db.Updateable(model).ExecuteCommandAsync();
            //根据更新结果设置返回状态。
            if (result.data > 0)
            {
                result.code = APIResultCode.success;
                result.msg = "修改成功";
            }
            else
            {
                result.code = APIResultCode.failed;
                result.msg = "修改失败";
            }
            return result;
        }
    }
}
